package com.example.mypigcar.utils;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.mypigcar.common.core.DirLocation;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


/**
 * @author yzl
 * @date 2021年5月21日 23:06:17
 * @Description: 阿里云OSS存储服务工具类
 */
public class OSSUtils {


    private static String accessKeyId = "LTAI5t99suzKHx7quL5QfznG";
    private static String accessSecret = "EGgtGMjDDbwMZSKFcKIt2aUgrqvwxi";
    private static String endpoint = "oss-cn-beijing.aliyuncs.com";
    private static String bucketName = "pigcar";
    private static String sufferOutUrl = "http://pigcar.oss-cn-beijing.aliyuncs.com/";


    /**
     * 上传文件
     * @param fileId id
     * @param file  文件
     * @return 文件URL
     */
    public static String uploadFile(String fileId, String dir,MultipartFile file) {
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = fileId + ext; //文件名称
        String objName = dir + fileName; //文件夹+文件名称

        if (upload(objName, file)) {
            String url = sufferOutUrl + objName;
            return url;
        } else {
            return null;
        }
    }


    /**
     * 上传到OSS服务器
     * @param objName 对象名   文件夹/文件id.扩展名
     * @param file 文件
     * @return 上传状态
     */
    private static Boolean upload(String objName, MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessSecret);

        try {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(file.getBytes());
            ossClient.putObject(bucketName, objName, inputStream);
            ossClient.shutdown();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("上传失败");
            ossClient.shutdown();
            return false;
        }
    }


    /**
     * 删除OSS文件服务器上的文件
     * @param filePath 文件位置
     */
    public static void delete(String filePath) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessSecret);
        if (ossClient.doesObjectExist(bucketName, filePath)) {
            System.out.println("文件存在");
            ossClient.deleteObject(bucketName, filePath);
            System.out.println("删除成功");
        }else {
            System.out.println("文件不存在");
        }
        ossClient.shutdown();
    }

}
